import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { mockExamApi, assessmentApi, trainingApi } from '../services/api'
import type { MockExam, ExamResult, Question } from '../types'
import './MockExamPanel.css'

interface MockExamPanelProps {
  userId: string
  onNavigateToPlan?: () => void  // 导航到计划创建的回调
  onTestComplete?: () => void  // 测试完成的回调
}

type ExamPhase = 'select' | 'taking' | 'result'

const MockExamPanel = ({ userId, onNavigateToPlan, onTestComplete }: MockExamPanelProps) => {
  const [phase, setPhase] = useState<ExamPhase>('select')
  const [exam, setExam] = useState<MockExam | null>(null)
  const [examResult, setExamResult] = useState<ExamResult | null>(null)
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)
  const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null)
  const [answers, setAnswers] = useState<Record<string, string>>({})
  const [selectedAnswer, setSelectedAnswer] = useState<string>('')
  const [timeRemaining, setTimeRemaining] = useState(0)
  const [timeSpent, setTimeSpent] = useState(0)
  const [isLoading, setIsLoading] = useState(false)

  // 创建模拟测试
  const createExam = async (examType: string) => {
    setIsLoading(true)
    try {
      const newExam = await mockExamApi.createExam(userId, examType)
      setExam(newExam)
      setTimeRemaining(newExam.time_limit)
      setPhase('taking')
      await loadQuestion(0, newExam.question_ids)
    } catch (error) {
      console.error('创建测试失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 加载题目
  const loadQuestion = async (index: number, questionIds: string[]) => {
    if (index >= questionIds.length) {
      // 所有题目完成，提交测试
      await submitExam()
      return
    }

    const questionId = questionIds[index]
    try {
      // 直接根据题目ID获取题目
      const question = await trainingApi.getQuestionById(questionId)
      setCurrentQuestion(question)
      setCurrentQuestionIndex(index)
      setSelectedAnswer(answers[questionId] || '')
    } catch (error) {
      console.error('加载题目失败:', error)
      // 如果失败，使用默认题目结构
      setCurrentQuestion({
        question_id: questionId,
        session_id: 'exam_session',
        content: '题目加载中...',
        options: [],
        type: 'single_choice',
        difficulty: 'medium',
        knowledge_points: []
      })
    }
  }

  // 保存答案
  const saveAnswer = () => {
    if (!currentQuestion || !selectedAnswer) return

    const newAnswers = {
      ...answers,
      [currentQuestion.question_id]: selectedAnswer,
    }
    setAnswers(newAnswers)
  }

  // 下一题
  const nextQuestion = () => {
    if (!exam || !currentQuestion) return

    saveAnswer()
    const nextIndex = currentQuestionIndex + 1
    loadQuestion(nextIndex, exam.question_ids)
  }

  // 上一题
  const prevQuestion = () => {
    if (currentQuestionIndex <= 0 || !exam) return

    saveAnswer()
    const prevIndex = currentQuestionIndex - 1
    loadQuestion(prevIndex, exam.question_ids)
  }

  // 提交测试
  const submitExam = async () => {
    if (!exam) return

    saveAnswer()
    setIsLoading(true)
    try {
      const result = await mockExamApi.submitExam(
        exam.exam_id,
        userId,
        answers,
        timeSpent
      )
      setExamResult(result)
      setPhase('result')
      
      // 标记测试完成
      if (onTestComplete) {
        onTestComplete()
      }
    } catch (error) {
      console.error('提交测试失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 计时器
  useEffect(() => {
    if (phase !== 'taking' || timeRemaining <= 0) return

    const timer = setInterval(() => {
      setTimeRemaining((prev) => {
        if (prev <= 1) {
          // 时间到，自动提交
          submitExam()
          return 0
        }
        return prev - 1
      })
      setTimeSpent((prev) => prev + 1)
    }, 1000)

    return () => clearInterval(timer)
  }, [phase, timeRemaining])

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }

  return (
    <div className="mock-exam-panel">
      <AnimatePresence mode="wait">
        {phase === 'select' && (
          <motion.div
            key="select"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            className="exam-select"
          >
            <h2>选择测试类型</h2>
            <div className="exam-options">
              <div className="exam-option-card" onClick={() => createExam('quick')}>
                <div className="exam-icon">⚡</div>
                <h3>快速评估</h3>
                <p>20题 · 约15-20分钟</p>
                <p className="exam-desc">适合快速了解当前水平</p>
              </div>
              <div className="exam-option-card" onClick={() => createExam('standard')}>
                <div className="exam-icon">📊</div>
                <h3>标准评估</h3>
                <p>50题 · 约40-50分钟</p>
                <p className="exam-desc">全面评估各科目掌握情况</p>
              </div>
              <div className="exam-option-card" onClick={() => createExam('full')}>
                <div className="exam-icon">🎯</div>
                <h3>完整模拟</h3>
                <p>100题 · 约90分钟</p>
                <p className="exam-desc">完整模拟法考环境</p>
              </div>
            </div>
          </motion.div>
        )}

        {phase === 'taking' && exam && currentQuestion && (
          <motion.div
            key="taking"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="exam-taking"
          >
            {/* 顶部信息栏 */}
            <div className="exam-header">
              <div className="exam-progress">
                <span>
                  题目 {currentQuestionIndex + 1} / {exam.question_count}
                </span>
                <div className="progress-bar">
                  <div
                    className="progress-fill"
                    style={{
                      width: `${((currentQuestionIndex + 1) / exam.question_count) * 100}%`,
                    }}
                  ></div>
                </div>
              </div>
              <div className="exam-timer">
                <span className={timeRemaining < 300 ? 'timer-warning' : ''}>
                  {formatTime(timeRemaining)}
                </span>
              </div>
            </div>

            {/* 题目内容 */}
            <div className="exam-question-card">
              <div className="question-header">
                <span className="question-category">{currentQuestion.category || '综合'}</span>
                <span className="question-difficulty">
                  {currentQuestion.difficulty || 'medium'}
                </span>
              </div>

              <div className="question-content">
                <h3>{currentQuestion.content}</h3>
              </div>

              {currentQuestion.options && (
                <div className="question-options">
                  {currentQuestion.options.map((option, index) => (
                    <button
                      key={index}
                      className={`option-button ${
                        selectedAnswer === option ? 'selected' : ''
                      }`}
                      onClick={() => setSelectedAnswer(option)}
                    >
                      {option}
                    </button>
                  ))}
                </div>
              )}

              {/* 导航按钮 */}
              <div className="exam-navigation">
                <button
                  className="nav-button"
                  onClick={prevQuestion}
                  disabled={currentQuestionIndex === 0}
                >
                  上一题
                </button>
                <div className="nav-info">
                  <span>
                    已答题: {Object.keys(answers).length} / {exam.question_count}
                  </span>
                </div>
                {currentQuestionIndex < exam.question_count - 1 ? (
                  <button className="nav-button primary" onClick={nextQuestion}>
                    下一题
                  </button>
                ) : (
                  <button className="nav-button primary submit" onClick={submitExam}>
                    提交测试
                  </button>
                )}
              </div>
            </div>
          </motion.div>
        )}

        {phase === 'result' && examResult && (
          <motion.div
            key="result"
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="exam-result"
          >
            {/* 知识阶段展示 */}
            <div className="stage-card">
              <div className="stage-icon">{examResult.knowledge_stage.main_stage.icon}</div>
              <h2>{examResult.knowledge_stage.main_stage.name}</h2>
              <div className="stage-score">
                <span className="score-value">{examResult.accuracy.toFixed(1)}</span>
                <span className="score-label">分</span>
              </div>
              <p className="stage-description">
                {examResult.knowledge_stage.main_stage.description}
              </p>
              <p className="stage-advice">{examResult.knowledge_stage.main_stage.advice}</p>
            </div>

            {/* 详细统计 */}
            <div className="result-details">
              <h3>测试详情</h3>
              <div className="detail-grid">
                <div className="detail-item">
                  <span className="detail-label">总题数</span>
                  <span className="detail-value">{examResult.total_questions}</span>
                </div>
                <div className="detail-item">
                  <span className="detail-label">正确数</span>
                  <span className="detail-value">{examResult.correct_count}</span>
                </div>
                <div className="detail-item">
                  <span className="detail-label">准确率</span>
                  <span className="detail-value">{examResult.accuracy.toFixed(1)}%</span>
                </div>
                <div className="detail-item">
                  <span className="detail-label">用时</span>
                  <span className="detail-value">{formatTime(examResult.time_spent)}</span>
                </div>
              </div>

              {/* 科目表现 */}
              {examResult.knowledge_stage.weak_subjects.length > 0 && (
                <div className="weak-subjects">
                  <h4>需要加强的科目</h4>
                  <div className="subject-list">
                    {examResult.knowledge_stage.weak_subjects.map((subject, index) => (
                      <div key={index} className="subject-item weak">
                        <span>{subject.subject}</span>
                        <span>{subject.accuracy.toFixed(1)}%</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {examResult.knowledge_stage.strong_subjects.length > 0 && (
                <div className="strong-subjects">
                  <h4>表现较好的科目</h4>
                  <div className="subject-list">
                    {examResult.knowledge_stage.strong_subjects.map((subject, index) => (
                      <div key={index} className="subject-item strong">
                        <span>{subject.subject}</span>
                        <span>{subject.accuracy.toFixed(1)}%</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 学习建议 */}
              {examResult.recommendations.length > 0 && (
                <div className="recommendations">
                  <h4>学习建议</h4>
                  <ul>
                    {examResult.recommendations.map((rec, index) => (
                      <li key={index}>{rec}</li>
                    ))}
                  </ul>
                </div>
              )}
            </div>

            {/* 操作按钮 */}
            <div className="result-actions">
              <button
                className="action-button primary"
                onClick={() => {
                  setPhase('select')
                  setExam(null)
                  setExamResult(null)
                  setAnswers({})
                  setCurrentQuestionIndex(0)
                  setTimeSpent(0)
                }}
              >
                再次测试
              </button>
              <button
                className="action-button"
                onClick={async () => {
                  // 基于评估结果创建学习计划
                  if (isLoading) return
                  
                  setIsLoading(true)
                  try {
                    // 根据测试结果推荐学习天数
                    let recommendedDays = 180
                    const accuracy = examResult.accuracy
                    
                    if (accuracy >= 80) {
                      recommendedDays = 60  // 高分用户，冲刺计划
                    } else if (accuracy >= 65) {
                      recommendedDays = 90  // 中等水平，强化计划
                    } else {
                      recommendedDays = 180  // 基础薄弱，标准计划
                    }
                    
                    // 调用创建学习计划API
                    const plan = await assessmentApi.createStudyPlan(recommendedDays, userId)
                    
                    // 显示成功消息
                    alert(
                      `学习计划创建成功！\n\n` +
                      `计划时长：${plan.duration_days}天\n` +
                      `每日学习：${plan.daily_targets.study_hours}小时\n` +
                      `每日题目：${plan.daily_targets.questions}题\n\n` +
                      `点击确定查看计划详情`
                    )
                    
                    // 如果有导航回调，调用它（导航到评估诊断页面）
                    if (onNavigateToPlan) {
                      onNavigateToPlan()
                    } else {
                      // 如果没有回调，也触发测试完成回调，让父组件处理导航
                      if (onTestComplete) {
                        onTestComplete()
                      }
                    }
                  } catch (error) {
                    console.error('创建学习计划失败:', error)
                    alert('创建学习计划失败，请稍后重试')
                  } finally {
                    setIsLoading(false)
                  }
                }}
                disabled={isLoading}
              >
                {isLoading ? '创建中...' : '创建学习计划'}
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {isLoading && (
        <div className="loading-overlay">
          <div className="loading-spinner"></div>
          <p>加载中...</p>
        </div>
      )}
    </div>
  )
}

export default MockExamPanel

